/**
 * 公共配置方法  wqs
 * @type {number}
 */
    //获取 doctor_im
    var usernameIM = utilModule.getQueryString("usernameIM")?utilModule.getQueryString("usernameIM"):null;

    //获取医生id
    var doctorid = utilModule.getQueryString("doctorid")?utilModule.getQueryString("doctorid"):console.log("未获取到医生错误");
    //获取医生 信息
    var doctor_info = new Object();
    if(typeof(doctorid)  !="undefined"){
	    utilModule.post({
	        url: "doctor/doctorDetail",
	        needJson: false,
	        data:{"doctorId":doctorid},
	        async: false,
	        success: function (response) {
	            doctor_info=response.doctor;
	        },
	        false:function (response) {
	            mui.alert("未获取到医生错误",'提示');
	            return false;
	        }
	    });
	    console.log(doctor_info);  	
    }
  

var ImUtilModule = (function() {

	return {

		/**
		 * 创建IM 连接
		 * 
		 */
		conn: function() {
			return conn = new WebIM.connection({
                isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
                https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
                url: WebIM.config.xmppURL,
                heartBeatWait: WebIM.config.heartBeatWait,
                autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
                autoReconnectInterval: WebIM.config.autoReconnectInterval,
                apiUrl: WebIM.config.apiURL,
                isAutoLogin: true
            });
		},

		/**
		 * login 登录
		 */
		login: function(connObj) {
				            //登录js
            $(function() {
                var IMusername   =USERIM?USERIM:mui.alert("登录环信未获取到IM");
                var IMpassword   =IMPWD?IMPWD:"xyyl123";    
                // 登录
                var options = { 
						apiUrl: WebIM.config.apiURL,
						user : IMusername,
						pwd : IMpassword,
						appKey: WebIM.config.appkey,
                    };
                connObj.open(options);
            });
		},
		/**
		 * close 退出
		 */
		close: function(connObj) {
           connObj.close();
		},
		/**
		 * 文本单聊
		 * @param connObj 
		 * @param IMid 聊天对象ID
		 * @param msg 聊天内容
		 */
		singleChat: function(connObj,IMid,msg1) {
			var chatlist = JSON.parse(utilModule.getStorage("chat_list1"));
			var id = connObj.getUniqueId();              // 生成本地消息id
			var msg = new WebIM.message('txt', id);      // 创建文本消息
			msg.set({
				msg: msg1,                  			// 消息内容
				to: IMid,                          		// 接收消息对象（用户id）
				roomType: false,
				ext:{'orderStutas':"3","uid":USERID},
				success: function (id, serverMsgId) {
					console.log('send private text Success');
				},
				fail: function(e){
					console.log("Send private text error");
				}
			});
			msg.body.chatType = 'singleChat';
			connObj.send(msg.body);
        },
		sendPrivateImg : function(connObj,IMid,type) {
			var chatlist = JSON.parse(utilModule.getStorage("chat_list1"));
			var id = connObj.getUniqueId();                   // 生成本地消息id
		    var msg = new WebIM.message('img', id);// 创建图片消息
		    var input 
		    if(type ==1){
		    	 input = document.getElementById('fileToUpload');  // 选择图片的input
		    }else{
		    	input = document.getElementById('fileToUpload2');  // 选择图片的input
		    }      
		    var file = WebIM.utils.getFileUrl(input);      // 将图片转化为二进制文件
		    var allowType = {
		        'jpg': true,
		        'gif': true,
		        'png': true,
		        'bmp': true,
		        'jpeg':true
		    };
		    document.getElementById('fileToUpload').value="";
		    document.getElementById('fileToUpload2').value="";
		    var mask = mui.createMask();
		    mask.show();//显示遮罩
		    if (file.filetype.toLowerCase() in allowType) {
		        var option = {
		            apiUrl: WebIM.config.apiURL,
		            file: file,
		            ext:{'orderStutas':"3","uid":USERID},
		            to: IMid,                       // 接收消息对象
		            roomType: false,
		            chatType: 'singleChat',
		            onFileUploadError: function () {      // 消息上传失败
		                console.log('onFileUploadError');
		            },
		            onFileUploadComplete: function (data) {   // 消息上传成功
		                console.log('onFileUploadComplete');
		                console.log(data);
		                var url = data.uri+"/"+data.entities[0].uuid;
		                //环信发图片
			            var  html = '<li class="pullRight">'+
			                            '<div class="picture"><img src="'+
			                                url+
			                            '" alt="" data-preview-src="" data-preview-group="1" ></div>'+
			                        '</li>'
				        $("#im_content").append(html);
				        mask.close();//关闭遮罩
				        mui.scrollTo(10000,500); 
				        var arr_message =   {
				                        [usernameIM]:[
				                            {
				                                "doctorid":doctor_info.doctorid,
				                                "usernameIM":usernameIM,
				                                "realname":doctor_info.realname,
				                                "time":new Date().getTime(),
				                                "msg":url,
				                                "type_role":4,
				                            }
				                        ]
				        }
				        if(chatlist != null && chatlist != "undefined" && chatlist != ''&& chatlist.length !=0){
				            if(chatlist[usernameIM]){
				                chatlist[usernameIM].push(arr_message[usernameIM][0]);
				            }else{
				                chatlist = $.extend({}, chatlist, arr_message );
				            }
				            utilModule.removeStorage("chat_list1");
				            utilModule.setStorage("chat_list1",JSON.stringify(chatlist));
				        }else{
				            utilModule.setStorage("chat_list1",JSON.stringify(arr_message));
				        }
		            },
		            success: function (data) {                // 消息发送成功
		            	mask.close();//关闭遮罩
		                console.log('Success');
		                console.log(data);

		            },
		            flashUpload: WebIM.flashUpload
		        };
		        msg.set(option);
		        connObj.send(msg.body);
		    }else{
		    	alert("不支持图片格式"+file.filetype);
		    	mask.close();//关闭遮罩
		    }
		},
		/**
		 * 监听推送消息
		 * @param listen 
		 */
        listen:function(connObj) {
        	console.log("开启监听");
 			connObj.listen({
                onOpened: function ( message ) {          //连接成功回调
                    // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
                    // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
                    // 则无需调用conn.setPresence();
                    if(message.accessToken != undefined){
	                    console.log("登录成功");
	                    console.log(message);
                    }else{
                    	mui.alert("登录失败");
                    	console.log("登录失败");
                    }


                },  
                onClosed: function ( message ) {},         //连接关闭回调chatlist
                onTextMessage: function ( message ) {
                	var chatlist = JSON.parse(utilModule.getStorage("chat_list1"));
                	console.log(message);
					var	arr_message	=	{
								    [message.from]:[
								        {
								            "doctorid":doctor_info.doctorid,
								            "usernameIM":message.from,
								            "realname":doctor_info.realname,
								            "time":new Date().getTime(),
								            "avatar":doctor_info.avatar,
								            "msg":message.data,
								            "type_role":2,
								        }
								    ]
					}
					console.log(arr_message);
					var chatlist = JSON.parse(utilModule.getStorage("chat_list1"));
					if(chatlist != null && chatlist != "undefined" && chatlist != ''&& chatlist.length !=0){
						if(chatlist[message.from] != null){
							chatlist[message.from].push(arr_message[message.from][0]);
						}else{
							chatlist = $.extend({}, chatlist, arr_message );
						}
						utilModule.removeStorage("chat_list1");
						utilModule.setStorage("chat_list1",JSON.stringify(chatlist));
					}else{
						utilModule.setStorage("chat_list1",JSON.stringify(arr_message));
					}
					var contact_chat =$("#im_content");
					if(contact_chat && message.from  == usernameIM){
						var html_chat = '<li class="pullLeft">'+
							                '<div class="doctorImg"><img src="'+arr_message[message.from][0].avatar+'" alt=""></div>'+
							                '<div class="dialogue">'+
							                    arr_message[message.from][0].msg+
							                '</div>'+
							            '</li>'
						contact_chat.append(html_chat);
					}
                },    //收到文本消息
                onEmojiMessage: function ( message ) {},   //收到表情消息
                onPictureMessage: function ( message ) {
                	var chatlist = JSON.parse(utilModule.getStorage("chat_list1"));
        	 		var pid ;
        	 		if(message.ext.pid){
        	 			pid=3;
        	 		}else{
        	 			pid=5;
        	 		}
					var	arr_message	=	{
								    [message.from]:[
								        {
								            "doctorid":doctor_info.doctorid,
								            "usernameIM":message.from,
								            "realname":doctor_info.realname,
								            "time":new Date().getTime(),
								            "avatar":doctor_info.avatar,
								            "type_role":pid,
								            "img":message.url,
								            "chufang_id":message.ext.pid,
								        }
								    ]
					}
					console.log(arr_message);
					var chatlist = JSON.parse(utilModule.getStorage("chat_list1"));
					if(chatlist != null && chatlist != "undefined" && chatlist != ''&& chatlist.length !=0){
						if(chatlist[message.from] != null){
							chatlist[message.from].push(arr_message[message.from][0]);
						}else{
							chatlist = $.extend({}, chatlist, arr_message );
						}
						utilModule.removeStorage("chat_list1");
						utilModule.setStorage("chat_list1",JSON.stringify(chatlist));
					}else{
						utilModule.setStorage("chat_list1",JSON.stringify(arr_message));
					}
					var contact_chat =$("#im_content");
					if( message.from  == usernameIM){
						if(contact_chat &&message.ext.pid){
							var html_chat = '<li class="pullLeft">'+
								                '<div class="doctorImg"><img src="'+arr_message[message.from][0].avatar+'" alt=""></div>'+
								                '<div class="picture3">'+
								                '<a class="inquiry-img" href="../onlineContinuation/drug-delivery.html?id='+message.ext.pid+'" onclick="window.location.href=&quot../onlineContinuation/drug-delivery.html?id='+message.ext.pid+'&quot"><img src="http://xinyuyl.oss-cn-beijing.aliyuncs.com/app/doctor/cfd1.png" alt="">'+
								                '</div>'+
								            '</li>'
							contact_chat.append(html_chat);
						}else{
							var html_chat = '<li class="pullLeft">'+
								                '<div class="doctorImg"><img src="'+arr_message[message.from][0].avatar+'" alt=""></div>'+
								                '<div class="picture2">'+
								                '<img src="'+arr_message[message.from][0].img+'" alt="" width=50% height=50%  data-preview-src="" data-preview-group="1" >'+
								                '</div>'+
								            '</li>'
							contact_chat.append(html_chat);
						}
                	 }
                	console.log(message);
                }, //收到图片消息
                onCmdMessage: function ( message ) {},     //收到命令消息
                onAudioMessage: function ( message ) {},   //收到音频消息
                onLocationMessage: function ( message ) {},//收到位置消息
                onFileMessage: function ( message ) {},    //收到文件消息
                onVideoMessage: function (message) {
                    var node = document.getElementById('privateVideo');
                    var option = {
                        url: message.url,
                        headers: {
                          'Accept': 'audio/mp4'
                        },
                        onFileDownloadComplete: function (response) {
                            var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
                            node.src = objectURL;
                        },
                        onFileDownloadError: function () {
                            console.log('File down load error.')
                        }
                    };
                    WebIM.utils.download.call(conn, option);
                },   //收到视频消息
                onPresence: function ( message ) {},       //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
                onRoster: function ( message ) {},         //处理好友申请
                onInviteMessage: function ( message ) {},  //处理群组邀请
                onOnline: function () {console.log()},                  //本机网络连接成功
                onOffline: function () {},                 //本机网络掉线
                onError: function ( message ) {
                	console.log(message);
                	if(message.type == 8){
                		mui.alert("您的帐号在其他地方登录");
                	}
                },          //失败回调
                onBlacklistUpdate: function (list) {       //黑名单变动
                    // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
                    console.log(list);
                },
                onReceivedMessage: function(message){},    //收到消息送达客户端回执
                onDeliveredMessage: function(message){},   //收到消息送达服务器回执
                onReadMessage: function(message){},        //收到消息已读回执
                onCreateGroup: function(message){},        //创建群组成功回执（需调用createGroupNew）
                onMutedMessage: function(message){}        //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
            });
        },
        /**
		 * 首页localStorage ,存
		 * @param listen 
		 */
        setIndexStorage:function(doctor) {
        	var list = utilModule.getStorage("index_doctor");
        	if(list != null && list != undefined && list != ''){
        		var obj = JSON.parse(list);
        		for (var i = obj.doctorlist.length - 1; i >= 0; i--) {
        			if(obj.doctorlist[i]["id"]==doctor.id){
        				return false;
        			}
        		}

        		obj.doctorlist.push(doctor);
        		var str_obj=JSON.stringify(obj);

        		utilModule.removeStorage("index_doctor");
        		utilModule.setStorage("index_doctor",str_obj);
        			
        	}else{

        		var str_obj=JSON.stringify(doctor);
        		var doctor_list = {"doctorlist":[doctor] }
        		utilModule.setStorage("index_doctor",JSON.stringify(doctor_list));
        	}
        },
        /**
		 * 首页localStorage ,取
		 * @param listen 
		 */
        getIndexStorage:function() {
        	var index_doctor = utilModule.getStorage("index_doctor");
        	if(index_doctor != "null" && index_doctor != "undefined" && index_doctor != ''){
				return JSON.parse(index_doctor);
        	}else{
        		return false;
        	}
        	
        },
		isLastChat:function(data,type) {
			var chat_num =0;
			if(data.length>0){
				var i = data.length- 1;
	        	for (i ; i >= 0; i--) {

	        			if(data[i]["type_role"]==1 ||data[i]["type_role"]==4){
	        				chat_num++
	        			}
	        	}
        	}
        	if(typeof(type)!="undefined"){
        		type=19;
        	}else{
        		type=20;
        	}
        	if(chat_num<type){
        		return 1;
        	}else{
        		return 0;
        	}
        	
        },
        /**
		 * 聊天页localStorage ,取
		 * @param listen 
		 */
        setChatStorage:function(data){
        	var list = utilModule.getStorage("Chat_doctor");
        	if(list != "null" && list != "undefined" && list != ''&& list.length !=0){
        		var obj = JSON.parse(list);
        		time_=eval(obj)[eval(obj).length-1]["time_"];  
        		obj.doctorlist.push(data);
        	}else{
        		var str_obj=JSON.stringify(data);
        		utilModule.setStorage("Chat_doctor",str_obj);
        	}
        },
        /**
		 * 聊天页localStorage ,取
		 * @param listen 
		 */
        getChatStorage:function(){
			var Chat_doctor = utilModule.getStorage("Chat_doctor");
        	if(Chat_doctor != "null" && Chat_doctor != "undefined" && Chat_doctor != ''&& Chat_doctor.length !=0){
				return JSON.parse(Chat_doctor);
        	}else{
        		return false;
        	}
        },
		/**
		 * 医生资料localStorage ,取
		 * @param listen 
		 */
        setDoctorStorage:function(data){
        	var list = utilModule.getStorage(data.usernameIM);
        	if(list != "null" && list != "undefined" && list != ''&& list.length !=0){
        		var obj = JSON.parse(list);
        		time_=eval(obj)[eval(obj).length-1]["time_"];  
        		obj.doctorlist.push(data);
        	}else{
        		var str_obj=JSON.stringify(data);
        		utilModule.setStorage("Chat_doctor",str_obj);
        	}
        },
	}
})();